package com.sy.musicapp.model

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sy.musicapp.intent.api.PlaylistApi
import com.sy.musicapp.intent.network.MusicAppNetwork
import com.sy.musicapp.showToast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

/**
 * 歌单模块ViewModel
 * @author SY
 * @since 2022-02-21 21:33
 **/
class PlaylistViewModel : ViewModel(), PlaylistApi {

    var playlists = MutableStateFlow(Playlist.Empty)
    var playlistId: String = ""
    var playlistMusics = MutableStateFlow(mutableListOf<Music>())


    override fun getPlaylist(uid: String) {
        if (uid.isBlank() || playlists.value != Playlist.Empty) return //判空
        viewModelScope.launch(Dispatchers.Main) {
            try {
                MusicAppNetwork.getPlaylist(uid).body()?.let {
                    playlists.value = it.toMutableList()
                }
            } catch (e: Exception) {
                "请求歌单列表失败".showToast()
                e.printStackTrace()
            }
        }
    }

    override fun getPlaylistMusic(index: Int) {
        val id = playlists.value[index].id
        if (id != playlistId) {
            viewModelScope.launch(Dispatchers.Main) {
                try {
                    MusicAppNetwork.getPlaylistMusic(id).body()?.let {
                        playlistMusics.value = it.toMutableList()
                        playlistId = id
                    }
                } catch (e: Exception) {
                    "请求歌单歌曲失败".showToast()
                    e.printStackTrace()
                }
            }
        }
    }

    override fun addPlaylist(name: String) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                MusicAppNetwork.addPlaylist(name).body()?.let {
                    playlists.value.add(it)
                }
            } catch (e: Exception) {
                "新建歌单失败".showToast()
                e.printStackTrace()
            }
        }
    }

    override fun delPlaylist(index: Int) {
        val id = playlists.value[index].id
        viewModelScope.launch(Dispatchers.Main) {
            try {
                MusicAppNetwork.delPlaylist(id).body()?.let {
                    playlists.value.removeAt(index)
                }
            } catch (e: Exception) {
                "删除歌单失败".showToast()
                e.printStackTrace()
            }
        }
    }

    fun resetAll() {
        playlists = MutableStateFlow(Playlist.Empty)
        playlistId = ""
        playlistMusics = MutableStateFlow(mutableListOf<Music>())
    }
}